package com.leetcode.array;

import java.util.HashMap;
import java.util.Map;

public class Leetcode76 {

    public String minWindow(String s, String t) {
        Map<Character, Integer> window = new HashMap<>();
        Map<Character, Integer> need = new HashMap<>();

        for (Character ch : t.toCharArray()) {
            need.put(ch, need.getOrDefault(ch, 0) + 1);
        }

        // 维护一个[left, right)的窗口
        int left = 0, right = 0;
        int start = 0, len = Integer.MAX_VALUE;
        int valid = 0;

        while (right < s.length()) {
            // 扩大right
            char cur = s.charAt(right);
            right++;

            if (need.containsKey(cur)) {
                window.put(cur, window.getOrDefault(cur, 0) + 1);
                if (need.get(cur).intValue() == window.get(cur).intValue()) {
                    valid++;
                }
            }

            // window中含有t里面的全部字符
            while (valid == need.size()) {
                if (right - left < len) {
                    start = left;
                    len = right - left;
                }
                char leftCur = s.charAt(left);
                left++;
                if (need.containsKey(leftCur)) {
                    if (need.get(leftCur).intValue() == window.get(leftCur).intValue()) {
                        valid--;
                    }
                    window.put(leftCur, window.get(leftCur) - 1);
                }
            }
        }

        return len == Integer.MAX_VALUE ? "" : s.substring(start, start + len);
    }

    public static void main(String[] args) {
        String S = "a", T = "a";
        System.out.println(new Leetcode76().minWindow(S, T));
    }

}
